import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as Resp;
import 'package:ty_smart_watch/bean/login_bean.dart';
import 'package:ty_smart_watch/bean/reset_password_bean.dart';
import 'package:ty_smart_watch/bean/sms_code_bean.dart';
import 'package:ty_smart_watch/common/images_url.dart';
import 'package:ty_smart_watch/utils/Log.dart';
import 'package:ty_smart_watch/utils/http_util.dart';

/// 用户注册页
class ForgotPasswordPage extends StatefulWidget {
  const ForgotPasswordPage({super.key});

  @override
  State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  bool _checked = false;
  bool _isCodeButtonDisabled = false;
  int _codeCountdownSeconds = 60;
  late Timer _codeCountdownTimer;
  bool _registerEnable = false;
  final TextEditingController _phoneTextController = TextEditingController();
  final TextEditingController _codeTextController = TextEditingController();
  final TextEditingController _pwdTextController = TextEditingController();
  final TextEditingController _requiredPwdTextController = TextEditingController();
  bool _obscureText = true;
  RegExp _passwordRegex = RegExp(r'^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[a-zA-Z\d\W_]{8,16}$');
  bool _pwdValid = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        // automaticallyImplyLeading: false,
      ),
      body: Container(
        margin: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "忘记密码",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF0C0C0C)),
            ),
            const SizedBox(height: 20),
            //手机号
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                // crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        controller: _phoneTextController,
                        onChanged: (v) {
                          _checkRegisterEnable();
                        },
                        decoration: const InputDecoration(
                            hintText: "请输入手机号",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                        ],
                        maxLines: 1,
                      ),
                    ),
                  ),
                  const SizedBox(width: 10)
                ],
              ),
            ),
            const SizedBox(height: 20), //手机号
            //验证码
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                // crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        controller: _codeTextController,
                        onChanged: (v) {
                          _checkRegisterEnable();
                        },
                        maxLength: 4,
                        decoration: const InputDecoration(
                            counterText: "",
                            hintText: "请输入验证码",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                        ],
                        maxLines: 1,
                      ),
                    ),
                  ),
                  const SizedBox(width: 6),
                  Container(
                    child: TextButton(
                      onPressed: () {
                        // 处理按钮点击事件
                        // 这里可以放置发送验证码的逻辑
                        _isCodeButtonDisabled ? null : _sendCode();
                      },
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(
                            _isCodeButtonDisabled ? Colors.grey : Colors.blue),
                        foregroundColor: MaterialStateProperty.all(Colors.white),
                        shape: MaterialStateProperty.all(
                          const RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                          ),
                        ),
                      ),
                      child: Text(_isCodeButtonDisabled ? "$_codeCountdownSeconds" : '发送验证码'),
                    ),
                  ),
                  const SizedBox(width: 10)
                ],
              ),
            ),
            const SizedBox(height: 20),
            //密码输入框
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        controller: _pwdTextController,
                        onChanged: (v) {
                          _checkPwdIsValid(v);
                          _checkRegisterEnable();
                        },
                        decoration: const InputDecoration(
                            hintText: "请设置新密码",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        obscureText: _obscureText,
                        maxLines: 1,
                      ),
                    ),
                  ),
                  Visibility(
                    visible: !_obscureText,
                    child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _obscureText = true;
                          });
                        },
                        child: Image.asset(ICON_PWD_VISIBILITY, width: 20, height: 20)),
                  ),
                  Visibility(
                    visible: _obscureText,
                    child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _obscureText = false;
                          });
                        },
                        child: Image.asset(ICON_PWD_INVISIBILITY, width: 20, height: 20)),
                  ),
                  const SizedBox(width: 10),
                ],
              ),
            ),
            const SizedBox(height: 20),
            Container(
              constraints: const BoxConstraints(minHeight: 0, maxHeight: double.infinity),
              alignment: Alignment.center,
              child: Text(
                "*8-16位字符，包含字母、数字、符号中至少2种",
                style: TextStyle(
                    color: _pwdValid ? const Color(0xFF969696) : const Color(0xFFEE9F41),
                    fontSize: 12),
              ),
            ),
            const SizedBox(height: 20),
            //确认密码输入框
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: TextField(
                  controller: _requiredPwdTextController,
                  onChanged: (v) {
                    _checkRegisterEnable();
                  },
                  decoration: const InputDecoration(
                      hintText: "请确认新密码",
                      hintStyle: TextStyle(
                        color: Color(0xFF969696),
                      ),
                      border: InputBorder.none),
                  obscureText: true,
                  maxLines: 1,
                ),
              ),
            ),
            const Expanded(child: SizedBox()),
            //设置新密码按钮
            GestureDetector(
              onTap: _registerEnable ? _resetPwd : null,
              child: Container(
                height: 50,
                padding: const EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                  //圆角半径
                  borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                  color: _registerEnable ? const Color(0xFF2A6FE5) : const Color(0xFF80A3DF),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "设置新密码",
                      style:
                          TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 60),
          ],
        ),
      ),
    );
  }

  _checkRegisterEnable() {
    if (_phoneTextController.text.isEmpty ||
        _codeTextController.text.length != 4 ||
        _pwdTextController.text.isEmpty ||
        _requiredPwdTextController.text.isEmpty ||
        _pwdTextController.text.length != _requiredPwdTextController.text.length) {
      setState(() {
        _registerEnable = false;
      });
    } else {
      setState(() {
        _registerEnable = true;
      });
    }
  }

  _resetPwd() async {
    Log.d(
        "设置新密码  >>  ${_phoneTextController.text}  ::  ${_codeTextController.text}  ::  ${_pwdTextController.text}  ::");
    SmartDialog.showLoading(msg: "请稍后...", clickMaskDismiss: false, backDismiss: false);
    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // print("传入的验证码：$code");
    var dio = HttpUtil.instance?.serviceDio();
    dio.options.headers['tenant-id'] = "1";
    Map<String, dynamic> data = {
      'mobile': _phoneTextController.text,
      'code': _codeTextController.text,
      'password': _pwdTextController.text,
    };
    Resp.Response response = await dio.put("/member/user/reset-password", data: data);
    print("设置新密码结果 ： $response");
    try {
      Map<String, dynamic> resetPasswordMap = jsonDecode(response.toString());
      ResetPasswordBean resetPasswordBean = ResetPasswordBean.fromJson(resetPasswordMap);

      if (resetPasswordBean.code == 0) {
        //密码修改成功
        SmartDialog.showToast("密码修改成功");
        Get.back();
      } else {
        SmartDialog.showToast(resetPasswordBean.msg ?? "密码修改失败");
      }
    } catch (e) {
      print("e: $e");
    } finally {
      SmartDialog.dismiss(status: SmartStatus.loading);
    }
  }

  _sendCode() async {
    Log.d("发送验证码");
    if (_phoneTextController.text.isEmpty) {
      Log.d("手机号码不能为空");
      return;
    }

    setState(() {
      _isCodeButtonDisabled = true;
      _codeCountdownSeconds = 60; // 重置倒计时
    });
    var dio = HttpUtil.instance?.serviceDio();
    dio.options.headers['tenant-id'] = "1";
    Map<String, dynamic> data = {
      'mobile': _phoneTextController.text,
      'scene': 4,
    };
    Resp.Response response = await dio.post("/member/auth/send-sms-code", data: data);
    print("验证码 ： $response"); //成功： {"code":0,"data":true,"msg":""}
    try {
      Map<String, dynamic> smsCodeMap = jsonDecode(response.toString());
      SmsCodeBean smsCodeBean = SmsCodeBean.fromJson(smsCodeMap);
      if (smsCodeBean.code == 0) {
        SmartDialog.showToast("短信发送成功");
      } else {
        SmartDialog.showToast(smsCodeBean.msg ?? "短信发送失败");
      }
    } catch (e) {
      print("e: $e");
    }
    _startCountdownTimer();
  }

  _checkPwdIsValid(String s) {
    // setState(() {
    //   _pwdValid = _passwordRegex.hasMatch(s);
    // });
  }

  _startCountdownTimer() {
    Log.d("验证码计时器");
    _codeCountdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_codeCountdownSeconds > 1) {
          _codeCountdownSeconds--;
        } else {
          _codeCountdownTimer.cancel();
          _isCodeButtonDisabled = false; // 计时结束后重新启用按钮
        }
      });
    });
  }
}
